package com.blog.util;

import com.blog.bean.User;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginUtil {

    /**
     * 访问接口时，检测用户是否已登录
     *
     * @param session
     * @param response
     * @return
     */
    public static User checkApiLogin(HttpSession session, HttpServletResponse response) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            try {
                response.sendError(401);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    /**
     * 访问页面时，检测用户是否已登录
     *
     * @param session
     * @param response
     * @return
     */
    public static User checkPageLogin(HttpSession session, HttpServletResponse response) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            try {
                response.sendRedirect("/blog/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return user;
    }

}
